from fastapi import APIRouter, HTTPException, Path, Query
from typing import List, Optional
from ..models import User, ApiResponse
from datetime import datetime

# 创建路由器
router = APIRouter(
    prefix="/api/users",
    tags=["users"],
    responses={404: {"description": "未找到"}},
)

# 模拟用户数据库
users_db = [
    User(
        id=1, 
        username="admin", 
        email="admin@example.com", 
        is_active=True, 
        created_at=datetime.fromisoformat("2023-01-01T00:00:00")
    ),
    User(
        id=2, 
        username="user1", 
        email="user1@example.com", 
        is_active=True, 
        created_at=datetime.fromisoformat("2023-01-02T00:00:00")
    ),
    User(
        id=3, 
        username="user2", 
        email="user2@example.com", 
        is_active=False, 
        created_at=datetime.fromisoformat("2023-01-03T00:00:00")
    ),
]

# 获取所有用户
@router.get("/", response_model=List[User])
async def get_users(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(10, ge=1, le=100, description="返回的最大记录数"),
    active: Optional[bool] = Query(None, description="按活跃状态筛选")
):
    filtered_users = users_db
    
    # 按活跃状态筛选
    if active is not None:
        filtered_users = [user for user in filtered_users if user.is_active == active]
    
    # 分页
    return filtered_users[skip : skip + limit]

# 获取单个用户
@router.get("/{user_id}", response_model=User)
async def get_user(user_id: int = Path(..., ge=1, description="用户ID")):
    user = next((user for user in users_db if user.id == user_id), None)
    if user is None:
        raise HTTPException(status_code=404, detail="用户未找到")
    return user

# 获取用户统计信息
@router.get("/stats", response_model=ApiResponse)
async def get_user_stats():
    total_users = len(users_db)
    active_users = sum(1 for user in users_db if user.is_active)
    inactive_users = total_users - active_users
    
    return ApiResponse(
        success=True,
        message="用户统计信息",
        data={
            "total": total_users,
            "active": active_users,
            "inactive": inactive_users,
            "timestamp": datetime.now().isoformat()
        }
    )